<template>
  <div class="payment-result">
    <div class="result-content">
      <!-- 成功状态 -->
      <div v-if="paymentData.status === 'success'" class="success-result">
        <div class="status-icon success">
          <el-icon><CircleCheckFilled /></el-icon>
        </div>
        <div class="status-title">支付成功</div>
        <!-- 金额显示部分 -->
        <div class="amount-display">
          <div class="amount-label">支付金额</div>
          <div class="amount-value">
            ¥ {{ paymentData.amount.toFixed(2) }}
          </div>
        </div>

        <!-- 倒计时提示 -->
        <div class="countdown-tips">
          <div class="countdown-text">
            <el-icon><Clock /></el-icon>
            <span>{{ countdown }}秒后自动退出系统</span>
          </div>
          <div class="countdown-progress">
            <div
              class="countdown-bar"
              :style="{ width: countdownProgress + '%' }"
            ></div>
          </div>
        </div>

        <div class="success-tips">
          <div class="tip-item">
            <el-icon><Check /></el-icon>
            <span>支付成功，您已完成本次门诊缴费</span>
          </div>
          <div class="tip-item">
            <el-icon><Check /></el-icon>
            <span>电子收据已生成，可在"我的缴费记录"中查看</span>
          </div>
          <div class="tip-item">
            <el-icon><Check /></el-icon>
            <span>如需纸质发票，请到收费窗口打印</span>
          </div>
        </div>
      </div>

      <!-- 失败状态 -->
      <div v-else class="failed-result">
        <div class="status-icon failed">
          <el-icon><CircleCloseFilled /></el-icon>
        </div>
        <div class="status-title">支付失败</div>

        <div class="error-message">{{ paymentData.errorMessage }}</div>

        <div class="suggestions">
          <div class="suggestions-title">建议操作</div>
          <div class="suggestions-list">
            <div
              class="suggestion-item"
              @click="$emit('change-payment-method')"
            >
              <div class="suggestion-icon">
                <el-icon><Refresh /></el-icon>
              </div>
              <div class="suggestion-content">
                <div class="suggestion-title">重新尝试支付</div>
                <div class="suggestion-desc">网络波动可能导致支付失败</div>
              </div>
            </div>
            <div
              class="suggestion-item"
              @click="$emit('change-payment-method')"
            >
              <div class="suggestion-icon">
                <el-icon><CreditCard /></el-icon>
              </div>
              <div class="suggestion-content">
                <div class="suggestion-title">更换支付方式</div>
                <div class="suggestion-desc">尝试使用其他支付方式完成支付</div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="action-buttons">
      <template v-if="paymentData.status === 'success'">
        <button class="secondary-button" @click="showPrintReceipt">
          <el-icon><Printer /></el-icon>
          打印凭证
        </button>
        <button class="primary-button" @click="handleExit">
          <el-icon><HomeFilled /></el-icon>
          立即退出 ({{ countdown }}s)
        </button>
      </template>
      <template v-else>
        <button
          class="secondary-button"
          @click="$emit('change-payment-method')"
        >
          <el-icon><Refresh /></el-icon>
          重新支付
        </button>
        <button class="primary-button" @click="$emit('change-payment-method')">
          <el-icon><CreditCard /></el-icon>
          更换支付方式
        </button>
      </template>
    </div>

    <!-- 缴费凭证打印弹窗 -->
    <el-dialog
      v-model="showPrintDialog"
      title="门诊缴费凭证"
      width="400px"
      :close-on-click-modal="false"
      center
    >
      <div class="receipts-container">
        <div
          v-for="(item, index) in examinationReceipts"
          :key="'exam-' + index"
          class="receipt-container"
        >
          <div class="receipt-header">
            <h3>门诊缴费凭证</h3>
            <div class="hospital-info">
              <p>智医云联</p>
              <p>自助服务系统</p>
            </div>
          </div>

          <!-- 二维码区域 -->
          <div class="qrcode-section">
            <div class="qrcode-container">
              <div class="qrcode-wrapper">
                <Qrcode
                  :key="'qrcode-' + index"
                  :qrUrlStr="item.receiptNo"
                  :width="120"
                  :height="120"
                />
                <div class="qrcode-number">
                  {{
                    item.paymentCode ||
                    item.receiptNo 
                  }}
                </div>
              </div>
            </div>
          </div>

          <div class="receipt-content">
            <!-- 患者信息 -->
            <div class="receipt-section">
              <h4>患者信息</h4>
              <div class="info-grid">
                <div class="info-row">
                  <span class="label">患者姓名：</span>
                  <span class="value">{{ paymentData.patientName }}</span>
                </div>
                <div class="info-row">
                  <span class="label">就诊号：</span>
                  <span class="value">{{ paymentData.visitNumber }}</span>
                </div>
              </div>
            </div>

            <!-- 检查项目信息 -->
            <div class="receipt-section">
              <h4>检查项目</h4>
              <div class="exam-details">
                <div class="exam-item">
                  <div class="exam-name">{{ item.exam_name }}</div>
                  <div class="exam-info">
                    <span class="exam-dept"
                      >检查科室：{{ item.department_name }}</span
                    >
                    <span class="exam-amount"
                      >金额：¥{{ item.unit_price.toFixed(2) }}</span
                    >
                  </div>
                  <div class="exam-desc" v-if="item.description">
                    {{ item.description }}
                  </div>                  
                </div>
              </div>
            </div>

            <!-- 缴费信息 -->
            <div class="receipt-section">
              <h4>缴费信息</h4>
              <div class="info-grid">
                <div class="info-row">
                  <span class="label">缴费单号：</span>
                  <span class="value">{{ item.receiptNo }}</span>
                </div>
                <div class="info-row">
                  <span class="label">缴费时间：</span>
                  <span class="value">{{
                    paymentData.paymentTime || currentTime
                  }}</span>
                </div>
                <div class="info-row">
                  <span class="label">支付方式：</span>
                  <span class="value">{{
                    getPaymentMethodText(paymentData.paymentMethod)
                  }}</span>
                </div>
              </div>
            </div>

            <div class="receipt-section">
              <h4 class="validity-title">检查凭证当日有效！</h4>
              <div class="tips-content validity-info">
                <p>
                  请凭此凭证到
                  <strong>{{ item.department_name }}</strong> 进行检查
                </p>
                <p>检查前请出示此凭证和就诊号</p>
                <p>如有疑问，请咨询导诊台工作人员</p>
              </div>
            </div>
          </div>

          <div class="receipt-footer">
            <div class="print-time">打印时间：{{ printTime }}</div>
            <div class="service-hotline">服务热线：400-123-4567</div>
          </div>

          <!-- 分割线（不是最后一个项目时显示） -->
          <div
            v-if="index < examinationReceipts.length - 1"
            class="receipt-divider"
          >
            <div class="divider-line"></div>
            <div class="divider-text">下一张凭证</div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showPrintDialog = false">取消</el-button>
          <el-button type="primary" @click="confirmPrint" :loading="printing">
            <el-icon><Printer /></el-icon>
            打印全部凭证 ({{ examinationReceipts.length }}张)
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { ElIcon } from "element-plus";
// 二维码组件
import Qrcode from "@/components/qrcode/Qrcode.vue";

// 通过 props 接收从父组件传递过来的 paymentData 这里是支付结果对象
const props = defineProps({
  paymentData: {
    type: Object,
    required: true,
  },
});

const emit = defineEmits(["change-payment-method"]);

const router = useRouter();

// 倒计时相关数据
const countdown = ref(60);
const countdownTimer = ref(null);

// 打印相关数据
const showPrintDialog = ref(false);
const printing = ref(false);
const printTime = ref("");
const currentTime = ref("");

// 计算倒计时进度
const countdownProgress = computed(() => {
  return (countdown.value / 60) * 100;
});


// 计算检查项目凭证数据 - 修改为使用 paidItems
const examinationReceipts = computed(() => {
  return (props.paymentData.paidItems || []).map((item, index) => ({
    ...item,
    receiptNo: item.item_receipt_no,
    paymentCode: item.item_receipt_no,
    // 适配原有模板字段
    exam_name: item.item_name,
    department_name: item.department_name,
    unit_price: item.amount, // 使用总金额
    description: item.specification,
  }));
});

// 获取支付方式文本
const getPaymentMethodText = (method) => {
  const methods = {
    wechat: "微信支付",
    alipay: "支付宝支付",
    unionpay: "银联支付",
    digitalrmb: "数字人民币支付",
  };
  return methods[method] || "未知支付方式";
};

// 修改金额显示 - 使用后端返回的金额
const displayAmount = computed(() => {
  return props.paymentData.personalPayment || props.paymentData.amount;
});

// 开始倒计时
const startCountdown = () => {
  countdownTimer.value = setInterval(() => {
    countdown.value--;

    if (countdown.value <= 0) {
      handleExit();
    }
  }, 1000);
};

// 停止倒计时
const stopCountdown = () => {
  if (countdownTimer.value) {
    clearInterval(countdownTimer.value);
    countdownTimer.value = null;
  }
};

// 显示打印凭证弹窗
const showPrintReceipt = () => {
  const now = new Date();
  printTime.value = now.toLocaleString("zh-CN");
  currentTime.value = now.toLocaleString("zh-CN");
  showPrintDialog.value = true;
};

// 确认打印
const confirmPrint = () => {
  printing.value = true;

  console.log("打印全部检查凭证:", examinationReceipts.value);

  // 模拟打印过程
  setTimeout(() => {
    printing.value = false;
    showPrintDialog.value = false;
    ElMessage.success(
      `成功打印 ${examinationReceipts.value.length} 张检查凭证`
    );
  }, 2000);
};

// 退出系统
const handleExit = () => {
  stopCountdown();
  console.log("退出系统，返回首页");
  // 这里可以添加退出逻辑，比如返回首页或关闭应用
  router.push("/self-service/home");
};

onMounted(() => {
  // 初始化当前时间
  currentTime.value = new Date().toLocaleString("zh-CN");

  // 只在成功状态启动倒计时
  if (props.paymentData.status === "success") {
    startCountdown();
  }
});

onUnmounted(() => {
  // 组件卸载时清除定时器
  stopCountdown();
});
</script>

<style lang="scss" scoped>
.payment-result {
  width: 100%;
}

.result-content {
  text-align: center;
}

.status-icon {
  margin-bottom: 20px;

  .el-icon {
    font-size: 80px;
  }

  &.success .el-icon {
    color: #10b981;
  }

  &.failed .el-icon {
    color: #dc2626;
  }
}

.status-title {
  font-size: 32px;
  font-weight: 700;
  margin-bottom: 16px;

  .success-result & {
    color: #10b981;
  }

  .failed-result & {
    color: #dc2626;
  }
}

.amount-display {
  margin-bottom: 30px;

  .amount-label {
    font-size: 16px;
    color: #64748b;
    margin-bottom: 8px;
  }

  .amount-value {
    font-size: 48px;
    font-weight: 700;
    color: #1e293b;
  }
}

/* 检查项目缴费明细样式 */
.examination-details {
  background: #f8fafc;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 24px;
  text-align: left;
}

.details-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 16px;
  text-align: center;
}

.details-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  background: white;
  border-radius: 8px;
  border-left: 4px solid #10b981;
}

.detail-left {
  flex: 1;

  .exam-name {
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 4px;
  }

  .exam-dept {
    font-size: 14px;
    color: #64748b;
  }
}

.detail-right {
  text-align: right;

  .exam-amount {
    font-size: 16px;
    font-weight: 700;
    color: #1e293b;
    margin-bottom: 4px;
  }

  .exam-receipt {
    font-size: 12px;
    color: #3b82f6;
    font-weight: 500;
    margin-bottom: 4px;
  }

  .exam-status {
    font-size: 12px;
    font-weight: 500;
    padding: 2px 8px;
    border-radius: 4px;

    &.success {
      background: #d1fae5;
      color: #065f46;
    }
  }
}

// 倒计时提示样式
.countdown-tips {
  background: #f0f9ff;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 24px;
  text-align: center;
}

.countdown-text {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  color: #0369a1;
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;

  .el-icon {
    color: #3b82f6;
  }
}

.countdown-progress {
  height: 6px;
  background: #e2e8f0;
  border-radius: 3px;
  overflow: hidden;

  .countdown-bar {
    height: 100%;
    background: linear-gradient(90deg, #10b981, #3b82f6);
    transition: width 1s linear;
    border-radius: 3px;
  }
}

.error-message {
  font-size: 18px;
  color: #ef4444;
  margin-bottom: 30px;
  background: #fef2f2;
  padding: 12px 20px;
  border-radius: 8px;
  display: inline-block;
}

.success-tips {
  background: #f0f9ff;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 30px;
  text-align: left;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 12px;
  color: #0369a1;
  margin-bottom: 12px;

  &:last-child {
    margin-bottom: 0;
  }

  .el-icon {
    color: #10b981;
    font-size: 16px;
  }
}

.suggestions {
  text-align: left;
}

.suggestions-title {
  font-size: 18px;
  font-weight: 600;
  color: #1e293b;
  margin-bottom: 20px;
  text-align: center;
}

.suggestions-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.suggestion-item {
  display: flex;
  align-items: flex-start;
  gap: 16px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 12px;
  border-left: 4px solid #3b82f6;
  cursor: pointer;
  transition: all 0.3s;

  &:hover {
    background: #f0f9ff;
    transform: translateX(4px);
  }
}

.suggestion-icon {
  width: 40px;
  height: 40px;
  background: #3b82f6;
  color: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
  flex-shrink: 0;
}

.suggestion-content {
  flex: 1;

  .suggestion-title {
    font-size: 16px;
    font-weight: 600;
    color: #1e293b;
    margin-bottom: 4px;
  }

  .suggestion-desc {
    font-size: 14px;
    color: #64748b;
  }
}

.action-buttons {
  display: flex;
  gap: 12px;
  margin-top: 32px;
  flex-wrap: wrap;
}

.secondary-button {
  flex: 1;
  min-width: 120px;
  height: 48px;
  background: white;
  color: #3b82f6;
  border: 2px solid #3b82f6;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s;

  &:hover {
    background: #f0f9ff;
    border-color: #1d4ed8;
  }
}

.primary-button {
  flex: 1;
  min-width: 160px;
  height: 48px;
  background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  transition: all 0.3s;

  &:hover {
    background: linear-gradient(135deg, #2563eb 0%, #1e40af 100%);
    box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
  }
}

/* 缴费凭证打印样式 */
.receipts-container {
  max-height: 70vh;
  overflow-y: auto;
}

.receipt-container {
  background: white;
  border: 2px solid #333;
  padding: 20px;
  font-family: "Courier New", monospace;
  margin-bottom: 0;

  &:last-child {
    margin-bottom: 0;
  }
}

.receipt-header {
  text-align: center;
  border-bottom: 2px dashed #333;
  padding-bottom: 15px;
  margin-bottom: 20px;
}

.receipt-header h3 {
  margin: 0 0 10px 0;
  font-size: 20px;
  font-weight: bold;
}

.hospital-info {
  font-size: 14px;
}

.hospital-info p {
  margin: 2px 0;
}

/* 二维码区域样式 */
.qrcode-section {
  text-align: center;
  margin: 15px 0;
  padding: 10px 0;
  border-bottom: 1px dashed #ccc;
}

.qrcode-container {
  display: flex;
  justify-content: center;
}

.qrcode-wrapper {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.qrcode-number {
  font-size: 12px;
  font-weight: bold;
  color: #333;
  text-align: center;
  margin-top: 5px;
}

.receipt-content {
  margin-bottom: 20px;
}

.receipt-section {
  margin-bottom: 20px;

  .validity-title {
    text-align: center;
    margin-bottom: 10px;
  }

  .validity-info {
    line-height: 1.6;
  }

  .validity-info p {
    margin: 8px 0;
    font-size: 13px;
  }
}

.receipt-section h4 {
  margin: 0 0 10px 0;
  font-size: 16px;
  font-weight: bold;
  border-bottom: 1px solid #ccc;
  padding-bottom: 5px;
}

.info-grid {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
}

.info-row .label {
  font-weight: bold;
  min-width: 80px;
}

.info-row .value {
  text-align: right;
  flex: 1;
  margin-left: 10px;
}

.fee-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.fee-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 14px;
  padding: 4px 0;
}

.fee-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  border-top: 1px solid #333;
  padding-top: 8px;
  margin-top: 8px;
}

.total-amount {
  color: #f56c6c;
}

.receipt-divider {
  text-align: center;
  margin: 20px 0;
  padding: 10px 0;

  .divider-line {
    height: 1px;
    background: repeating-linear-gradient(
      90deg,
      #ccc,
      #ccc 4px,
      transparent 4px,
      transparent 8px
    );
    margin-bottom: 8px;
  }

  .divider-text {
    color: #999;
    font-size: 12px;
  }
}

.exam-details {
  .exam-item {
    padding: 10px;
    background: #f9f9f9;
    border-radius: 4px;

    .exam-name {
      font-size: 16px;
      font-weight: bold;
      margin-bottom: 8px;
      color: #333;
    }

    .exam-info {
      display: flex;
      justify-content: space-between;
      margin-bottom: 6px;
      font-size: 14px;

      .exam-dept {
        color: #666;
      }

      .exam-amount {
        color: #e74c3c;
        font-weight: bold;
      }
    }

    .exam-desc {
      font-size: 13px;
      color: #888;
      margin-bottom: 4px;
      line-height: 1.4;
    }

    .exam-time {
      font-size: 13px;
      color: #2ecc71;
      font-weight: 500;
    }
  }
}

.receipt-footer {
  border-top: 2px dashed #333;
  padding-top: 15px;
  text-align: center;
  font-size: 12px;
}

.print-time {
  margin-bottom: 8px;
}

.service-hotline {
  color: #666;
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 20px;
}

@media (max-width: 768px) {
  .status-icon .el-icon {
    font-size: 60px;
  }

  .status-title {
    font-size: 28px;
  }

  .amount-value {
    font-size: 36px;
  }

  .error-message {
    font-size: 16px;
  }

  .action-buttons {
    flex-direction: column;
  }

  .secondary-button,
  .primary-button {
    flex: 1;
  }

  .receipt-container {
    padding: 15px;
  }

  .info-row {
    font-size: 12px;
  }

  .qrcode-wrapper {
    :deep(.qrcode) {
      width: 100px !important;
      height: 100px !important;
    }
  }

  .detail-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .detail-right {
    text-align: left;
    width: 100%;
  }
}
</style>